
package com.alibaba.moco.gitlab;

import java.io.IOException;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



import com.alibaba.moco.util.PropertiesUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * 类GitlabApiUtil.java的实现描述：TODO 类实现描述 
 * @author wb-lj240895 2016年12月7日 上午10:53:30
 */
public class GitlabApiUtil {
	private static final Logger logger = LoggerFactory.getLogger(GitlabApiUtil.class);
	
	/**
	 * 获取gitlab资源并转换成字符串
	 * <a>http://gitlab.alibaba-inc.com/api/v3/projects/199287/repository/files?private_token=xzHzKzxjYSnLaqkTwdu5&file_path=webapp/index.html&ref=master</a>
	 * @param filePath
	 * @return
	 */
	public static GitlabFileResVo getFileContent(String filePath){
		String url = String.format("http://%s/api/v3/projects/%s/repository/files?private_token=%s&file_path=%s&ref=%s",
				PropertiesUtils.getAttribute("gitlab.url"),
				PropertiesUtils.getAttribute("gitlab.project.id"),
				PropertiesUtils.getAttribute("gitlab.token"),
				filePath,
				PropertiesUtils.getAttribute("gitlab.branch"));
		try {
			JSONObject json = JSONObject.fromObject(reqeustUrl(url));
			GitlabFileResVo resVo = (GitlabFileResVo) JSONObject.toBean(json, GitlabFileResVo.class);
			if (resVo != null && resVo.getContent() != null){
				resVo.setContent(decBase64(resVo.getContent()));
				return resVo;
			}
		} catch (Exception e) {
			logger.error("Gitlab请求失败{}",url,e);
		}
		return null;
	}
	/**
	 * 获取当前分支信息  包括版本id
	 * @return
	 */
    public static GitlabBranchResVo getBranchInfo(){
    	String url = String.format("http://%s/api/v3/projects/%s/repository/branches/%s?private_token=%s",
    			PropertiesUtils.getAttribute("gitlab.url"),
				PropertiesUtils.getAttribute("gitlab.project.id"),
				PropertiesUtils.getAttribute("gitlab.branch"),
				PropertiesUtils.getAttribute("gitlab.token"));
    	JSONObject json = null;
    	try {
			json = JSONObject.fromObject(reqeustUrl(url));
		} catch (Exception e) {
			logger.error("Gitlab请求失败{}",url,e);
		}
    	if (json != null){
    		return (GitlabBranchResVo)JSONObject.toBean(json, GitlabBranchResVo.class);
    	}
    	return null;
    }
    /**
     * <a>http://gitlab.alibaba-inc.com/api/v3/projects/199287/repository/commits/9c5b9935f47f283183e30ab04e5894e2eb7e2b5f/diff?private_token=xzHzKzxjYSnLaqkTwdu5</a>
     * 获取提交版本差异
     * @param commitId
     * @return
     */
    @SuppressWarnings({ "deprecation", "unchecked" })
	public static List<GItlabBranchDiffResVo> getCommitDiff(String commitId){
    	String url = String.format("http://%s/api/v3/projects/%s/repository/commits/%s/diff?private_token=%s",
    			PropertiesUtils.getAttribute("gitlab.url"),
				PropertiesUtils.getAttribute("gitlab.project.id"),
				commitId,
				PropertiesUtils.getAttribute("gitlab.token"));
    	JSONArray json = null;
    	try {
			json = JSONArray.fromObject(reqeustUrl(url));
		} catch (Exception e) {
			logger.error("Gitlab请求失败{}",url,e);
		}
    	if (json != null){
    		//TODO:替换过时的tolist方法
    		return JSONArray.toList(json, GItlabBranchDiffResVo.class);
    	}
    	return null;
    }
	
	/**
	 * 请求并返回json字符串
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
    private static String reqeustUrl(String url) {
        String result = null;// 返回结果
        int times = 1;// 尝试次数
        
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        while (StringUtils.isBlank(result) && times <= 3) {
            logger.debug("第 {} 次获取gitlab资源,url:{}", times, url);
           
            try {
                CloseableHttpResponse res = client.execute(get);
                HttpEntity entity = res.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                //未获取到数据时等待5秒
                if (StringUtils.isBlank(result)){
                    Thread.sleep(5000);
                }
            } catch (Exception e) {
                logger.warn("第 {} 次请求gitlab资源失败,url:{}", times, url);
            }
            times ++; 
        }
        try {
            client.close();
        } catch (IOException e) {
            logger.warn("请求连接关闭失败", e);
        }
        return result;
    }
	/**
	 * base64解码
	 * @param base64
	 * @return
	 */
	private static String decBase64(String base64){
		if (StringUtils.isBlank(base64)) 
			return null;
		byte[] base = Base64.decodeBase64(base64);
		return new String(base);
	}
}
